//
//  MapViewController.m
//  MyMovie
//
//  Created by lanou on 15/9/21.
//  Copyright (c) 2015年 HeQiangQiang. All rights reserved.
//

#import "MapViewController.h"


@interface MapViewController ()<BMKMapViewDelegate,BMKGeoCodeSearchDelegate,BMKLocationServiceDelegate,BMKPoiSearchDelegate>
@property (strong, nonatomic) BMKMapView *mapView;
@property (strong, nonatomic) BMKLocationService *locService;
@property (strong, nonatomic) BMKPoiSearch *poisearch;
@property (strong, nonatomic) UITextField *cityText;
@property (strong, nonatomic) UITextField *keyText;
@property (strong, nonatomic) BMKGeoCodeSearch *geocodesearch;
@property (assign, nonatomic) NSInteger page;

@end

@implementation MapViewController
- (void)dealloc {
    if (_mapView) {
        _mapView = nil;
    }
    if (_poisearch != nil) {
        _poisearch = nil;
    }
    if (_geocodesearch != nil) {
        _geocodesearch = nil;
    }
}
-(void)viewWillDisappear:(BOOL)animated
{
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
    _poisearch.delegate = nil;
    _geocodesearch.delegate = nil;
}
-(void)viewWillAppear:(BOOL)animated {
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    // 添加一个PointAnnotation
    BMKPointAnnotation* annotation = [[BMKPointAnnotation alloc]init];
    CLLocationCoordinate2D coor;
    coor.latitude = [self.coordinate[@"latitude"] doubleValue];
    coor.longitude = [self.coordinate[@"longitude"] doubleValue];
    annotation.coordinate = coor;
    annotation.title = self.name;
    [_mapView addAnnotation:annotation];
    
    //设置定位精确度，默认：kCLLocationAccuracyBest
    [BMKLocationService setLocationDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    //指定最小距离更新(米)，默认：kCLDistanceFilterNone
    [BMKLocationService setLocationDistanceFilter:100.f];
    
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    //启动LocationService
    [_locService startUserLocationService];
    
    
   
    //附近所有电影院
    _poisearch = [[BMKPoiSearch alloc]init];
    _cityText.text = @"上海";
    _keyText.text  = @"电影院";
    // 设置地图级别
    [_mapView setZoomLevel:13];
    _mapView.isSelectedAnnotationViewFront = YES;
    _poisearch.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
}
#pragma mark implement BMKSearchDelegate
- (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult*)result errorCode:(BMKSearchErrorCode)error
{
    // 清楚屏幕中所有的annotation
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    
    if (error == BMK_SEARCH_NO_ERROR) {
        NSMutableArray *annotations = [NSMutableArray array];
        for (int i = 0; i < result.poiInfoList.count; i++) {
            BMKPoiInfo* poi = [result.poiInfoList objectAtIndex:i];
            BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
            item.coordinate = poi.pt;
            item.title = poi.name;
            [annotations addObject:item];
        }
        [_mapView addAnnotations:annotations];
        [_mapView showAnnotations:annotations animated:YES];
    } else if (error == BMK_SEARCH_AMBIGUOUS_ROURE_ADDR){
        NSLog(@"起始点有歧义");
    } else {
        // 各种情况的判断。。。
    }
}

- (void)willStartLocatingUser {
    NSLog(@"%f",_locService.userLocation.location.coordinate.latitude);
}
//实现相关delegate 处理位置信息更新
//处理方向变更信息
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    //普通态
    //以下_mapView为BMKMapView对象
    _mapView.showsUserLocation = YES;//显示定位图层
    [_mapView updateLocationData:userLocation];
    //NSLog(@"heading is %@",userLocation.heading);
}
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    //普通态
    //以下_mapView为BMKMapView对象
    _mapView.showsUserLocation = YES;//显示定位图层
    [_mapView updateLocationData:userLocation];
    [_mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];//自动跟随的核心
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
}

- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
//    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
//        BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
//        newAnnotationView.pinColor = BMKPinAnnotationColorGreen;
//        newAnnotationView.animatesDrop = YES;// 设置该标注点动画显示
//        return newAnnotationView;
//    }
    NSString *AnnotationViewID = @"annotationViewID";
    //根据指定标识查找一个可被复用的标注View，一般在delegate中使用，用此函数来代替新申请一个View
    BMKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    if (annotationView == nil) {
        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        ((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed;
        ((BMKPinAnnotationView*)annotationView).animatesDrop = YES;
    }
    
    annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
    annotationView.annotation = annotation;
    annotationView.canShowCallout = TRUE;
    return annotationView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    _mapView = [[BMKMapView alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:_mapView];
    UIButton *button = [UIButton buttonWithType:(UIButtonTypeSystem)];
    button.frame = CGRectMake(250, 64, 40, 40);
    [button setTitle:@"卫星" forState:(UIControlStateNormal)];
    [button setTitle:@"普通" forState:(UIControlStateSelected)];
    [button addTarget:self action:@selector(button:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:button];
    
    UIButton *search = [UIButton buttonWithType:(UIButtonTypeSystem)];
    search.frame = CGRectMake(170, 64, 40, 40);
    [search setTitle:@"搜索" forState:(UIControlStateNormal)];
    [search addTarget:self action:@selector(search:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:search];
    
    UIButton *more = [UIButton buttonWithType:(UIButtonTypeSystem)];
    more.frame = CGRectMake(210, 64, 40, 40);
    [more setTitle:@"更多" forState:(UIControlStateNormal)];
    [more addTarget:self action:@selector(startFollowing:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:more];
    
    _cityText = [[UITextField alloc] initWithFrame:CGRectMake(10, 64, 80, 40)];
    _cityText.borderStyle = 3;
    [self.view addSubview:_cityText];
    _keyText = [[UITextField alloc] initWithFrame:CGRectMake(90, 64, 80, 40)];
    _keyText.borderStyle = 3;
    [self.view addSubview:_keyText];
}
#pragma mark implement BMKSearchDelegate
-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error {
    
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == 0) {
        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
        item.coordinate = result.location;
        item.title = result.address;
        [_mapView addAnnotation:item];
        _mapView.centerCoordinate = result.location;
        NSString *showmeg = [NSString stringWithFormat:@"%@",item.title];
        _cityText.text = [showmeg substringToIndex:2];
        
        _page = 0;
        BMKNearbySearchOption *citySearchOption = [[BMKNearbySearchOption alloc]init];
        citySearchOption.pageIndex = _page;
        citySearchOption.pageCapacity = 10;
        citySearchOption.location = CLLocationCoordinate2DMake(_locService.userLocation.location.coordinate.latitude, _locService.userLocation.location.coordinate.longitude);
        citySearchOption.radius= 10000;
        
        citySearchOption.keyword = _keyText.text;
        NSLog(@"%@",citySearchOption.keyword);
        BOOL flag2 = [_poisearch poiSearchNearBy:citySearchOption];
    }
}
- (void)button:(UIButton *)button {
    button.selected = !button.selected;
    if (button.selected) {
        [_mapView setMapType:BMKMapTypeSatellite];//切换为卫星图
    } else {
        [_mapView setMapType:BMKMapTypeStandard]; //切换为普通地图
    }
}
//搜索附近
- (void)search:(UIButton *)button {

//    [_locService startUserLocationService];
//    _mapView.showsUserLocation = NO;//先关闭显示的定位图层
//    _mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
//    _mapView.showsUserLocation = YES;//显示定位图层
  
    [self.view endEditing:YES];
    _geocodesearch = [[BMKGeoCodeSearch alloc]init];
    _geocodesearch.delegate = self;
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0, 0};
    pt = (CLLocationCoordinate2D){_locService.userLocation.location.coordinate.latitude, _locService.userLocation.location.coordinate.longitude};
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeocodeSearchOption.reverseGeoPoint = pt;
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
    if(flag)
    {
        NSLog(@"反geo检索发送成功");
    }
    else
    {
        NSLog(@"反geo检索发送失败");
    }
}
//跟随态
-(void)more:(UIButton *)button {
    NSLog(@"进入跟随态");
    _page++;
    BMKNearbySearchOption *citySearchOption = [[BMKNearbySearchOption alloc]init];
    citySearchOption.pageIndex = _page;
    citySearchOption.pageCapacity = 10;
    citySearchOption.location = CLLocationCoordinate2DMake(_locService.userLocation.location.coordinate.latitude, _locService.userLocation.location.coordinate.longitude);
    citySearchOption.radius= 10000;
    citySearchOption.keyword = _keyText.text;
    BOOL flag2 = [_poisearch poiSearchNearBy:citySearchOption];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
